<%
# Copyright (C) 2013 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
%>
<% launch_token = SecureRandom.uuid %>
<script>
  window.addEventListener('message', function(event) {
    var iframes = document.getElementsByTagName('iframe'),
      iframe;
    for (var i=0, l=iframes.length; i < l; i++) {
        if (iframes[i].contentWindow === event.source) {
        iframe = iframes[i];
        break;
      }
    }
    if (!iframe) {return;}

    var data = JSON.parse(event.data)

    if (data.request_launch_url) {
      event.source.postMessage(JSON.stringify({launch_url: iframe.getAttribute('data-launch-url')}), '*');
      return;
    }

      if (data.quicklaunch) {
        event.source.postMessage(JSON.stringify({quicklaunch: <%= embedded_chat_quicklaunch_params.to_json.html_safe %>}), '*');
        return;
      }
    if (!data.width && data.width !== 0) {return;}
    if (data.width > document.documentElement.clientWidth / 2) {return;}
    iframe.style.width = data.width+'px';
    iframe.style.height = data.height+'px';
    iframe.style.bottom = data.bottom+'px';
  }, false);
</script>
<div data-tool-wrapper-id="<%= launch_token %>">
  <iframe
    data-launch-url="<%= full_url(context_url(@context, :context_external_tool_resource_selection_url, active_external_tool_by_id('chat').id, launch_type: 'course_navigation', launch_token: launch_token)) %>"
    style="position: fixed; right: 0; bottom: 0; width: 0; height: 0; border: 1px solid #808080; z-index: 100"
    src="<%= embedded_chat_url %>"
    title="{{#t}}Chat{{/t}}"></iframe>
</div>
